package org.dtrd.modules.doctor.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.aspect.annotation.AutoLog;
import org.dtrd.common.util.DateUtils;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.doctor.entity.bean.*;
import org.dtrd.modules.doctor.entity.po.DtrdEntRdDoctor;
import org.dtrd.modules.doctor.entity.request.LatestRecordRequest;
import org.dtrd.modules.doctor.service.IDtrdEntRdDoctorConcernPatientService;
import org.dtrd.modules.doctor.service.IDtrdEntRdDoctorService;
import org.dtrd.modules.doctor.service.IDtrdRlDoctorPatientService;
import org.dtrd.modules.doctor.service.IDtrdRlDoctorTeamDoctorService;
import org.dtrd.modules.record.entity.bean.PatientShortInfo;
import org.dtrd.modules.record.service.IDtrdViewRlPatientSugarValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

import static org.dtrd.common.constant.CommonConstant.OPERATE_TYPE_QUERY;

/**
 * @author qr
 * @date 2022/4/14 14:49
 */
@Api(tags = "医生首页信息")
@RestController
@RequestMapping("/doctor/index/")
@Slf4j
public class DoctorIndexController {

    @Autowired
    private IDtrdEntRdDoctorService doctorService;
    @Autowired
    private IDtrdRlDoctorTeamDoctorService doctorTeamDoctorService;
    @Autowired
    private IDtrdRlDoctorPatientService doctorPatientService;
    @Autowired
    private IDtrdEntRdDoctorConcernPatientService doctorConcernPatientService;
    @Autowired
    private IDtrdViewRlPatientSugarValueService patientSugarValueService;
    @Autowired
    private BaseCommonService baseCommonService;

    @ApiOperation("获取医生首页信息-动态实时部分")
    @GetMapping("dynamic/info")
    public Result<?> getDoctorIndexInfoDynamic(@RequestParam(required = false) Integer doctorId) {
        DoctorIndexDynamicInfo dynamicInfo;
        List<Integer> teamDoctorIdList = doctorTeamDoctorService.getTeamDoctorIdList(doctorId);
        if (CollectionUtil.isNotEmpty(teamDoctorIdList)) {
            dynamicInfo = doctorService.getDoctorIndexDynamicInfo(teamDoctorIdList);
        } else {
            dynamicInfo = doctorService.getDoctorIndexDynamicInfo(doctorId);
        }
        log.info("DoctorIndexController.getDoctorIndexInfoDynamic.[doctorId] " + doctorId + "; dynamicInfo=" + dynamicInfo);
        String logContent = String.format("获取医生首页信息-动态实时部分, %d", doctorId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(dynamicInfo);
    }

    @ApiOperation("获取医生首页信息")
    @GetMapping("info")
    public Result<?> getDoctorIndexInfo(@RequestParam(required = false) Integer doctorId) {
        DoctorIndexInfo indexInfo;
        // Integer teamId = doctorTeamDoctorService.getManageTeamId(doctorId);
        Integer teamId = Optional.ofNullable(doctorId).map(id -> doctorService.getById(id)).map(DtrdEntRdDoctor::getTeamId).orElse(null);
        if (teamId != null) {

//        List<Integer> teamDoctorIdList = doctorTeamDoctorService.getTeamDoctorIdList(doctorId);
//        if (CollectionUtil.isNotEmpty(teamDoctorIdList)) {
//            //  有团队返回团队成员及本人统计信息
//            for (Integer tmpDoctorId : teamDoctorIdList) {
//                DoctorIndexInfo tmpIndexInfo = doctorService.getDoctorIndexInfo(tmpDoctorId);
//                if (tmpIndexInfo != null) {
//                    indexInfo = tmpIndexInfo;
//                }
//            }
            indexInfo = doctorService.getTeamDoctorIndexInfo(teamId);
        } else {
            // 无团队直接查询本人所属信息
            indexInfo = doctorService.getDoctorIndexInfo(doctorId);
        }

        String logContent = String.format("获取医生首页信息，医生%d ", doctorId);
        baseCommonService.addLog(logContent + "; 团队ID=" + teamId, OPERATE_TYPE_QUERY);
        return Result.OK(indexInfo);
    }

    @ApiOperation("查询H5首页统计信息")
    @PostMapping("/patient/statistics")
    @ApiResponses(@ApiResponse(code = 0, message = "", response = DoctorH5StatisticsInfo.class))
    public Result<?> getH5Statistics(@ApiParam(value = "医生ID", required = true) @RequestParam Integer doctorId) {
        // 今日测量-未测量-扫码患者
        DoctorH5StatisticsInfo info = new DoctorH5StatisticsInfo();
        // 增加 团队查询逻辑 肖 2022-07-19 18:11:29
//         List<Integer> teamDoctorIdList = doctorTeamDoctorService.getTeamDoctorIdList(doctorId);
        // if (doctorId != null && CollectionUtil.isEmpty(teamDoctorIdList)) {
        //     if (teamDoctorIdList == null) {
        //         teamDoctorIdList = new ArrayList<>();
        //     }
        //     teamDoctorIdList.add(doctorId);
        // }

        List<Integer> teamDoctorIdList = getTeamDoctorIdList(doctorId);

        // 改为团队下全部患者总数  肖 2022-07-19 18:07:06
        // 全部患者数
        List<DoctorStatisticsItem> list = doctorPatientService.getPatientStatisticsV2(teamDoctorIdList);
        if (CollectionUtil.isNotEmpty(list)) {
            AtomicInteger summary = new AtomicInteger();
            list.stream().mapToInt(DoctorStatisticsItem::getSummary).forEach(count -> {
                summary.addAndGet(count);
            });
            int total = summary.get();

//            int total = list.get(0).getSummary();
            log.info("DoctorIndexController.getH5Statistics.[doctorId] 全部患者  list=" + list + "; total=" + total + "; ");
            // 改为团队下扫码患者总数 肖 2022-07-19 18:06:49
            // 扫码患者
            list = doctorPatientService.getScanPatientStatisticsV2(teamDoctorIdList);
            if (CollectionUtil.isNotEmpty(list)) {
                summary.set(0);
                list.stream().mapToInt(DoctorStatisticsItem::getSummary).forEach(count -> {
                    summary.addAndGet(count);
                });
                info.setScanQrcodeNum(summary.get());
                log.info("DoctorIndexController.getH5Statistics.[doctorId] 扫码患者 list=" + list);
//                info.setScanQrcodeNum(list.get(0).getSummary());
            }
            // 重点关注仅针对医生本人 与团队无关  肖 2022-07-19 18:06:29
            // 重点关注
            list = doctorConcernPatientService.getConcernPatientCount(doctorId, null);
            if (CollectionUtil.isNotEmpty(list)) {
                info.setImportantNum(list.get(0).getSummary());
            }
            // 改为团队下今日测量数  肖 2022-07-19 18:14:59
            // 今日测量患者列表
//            List<PatientShortInfo> patientShortInfoList = patientSugarValueService.getMeasurePatientList(doctorId, null, null);
            List<PatientShortInfo> patientShortInfoList = patientSugarValueService.getMeasurePatientListV2(teamDoctorIdList, null, DateUtils.formatDate());
            if (CollectionUtil.isNotEmpty(patientShortInfoList)) {
                info.setTodayMeasureNum(patientShortInfoList.size());
                log.info("DoctorIndexController.getH5Statistics.[doctorId] total=" + total + "; patientShortInfoList.size()=" + patientShortInfoList.size());
                if (total >= patientShortInfoList.size()) {
                    info.setUnMeasureNum(total - patientShortInfoList.size());
                } else {
                    info.setUnMeasureNum(0);
                }
            } else {
                info.setUnMeasureNum(total);
            }
            info.setMeasurePatientList(patientShortInfoList);
        }
        return Result.OK(info);
    }

    private List<Integer> getTeamDoctorIdList(Integer doctorId) {
        Integer teamId = Optional.ofNullable(doctorId).map(id -> doctorService.getById(id)).map(DtrdEntRdDoctor::getTeamId).orElse(null);
        log.info("DoctorIndexController.getTeamDoctorId.[doctorId] teamId={}", teamId);
        List<Integer> teamDoctorIdList;
        if (teamId != null) {
            teamDoctorIdList = doctorTeamDoctorService.getTeamDoctorIdListByTeamId(teamId);
        } else {
            teamDoctorIdList = doctorTeamDoctorService.getTeamDoctorIdList(doctorId);
        }

        if (doctorId != null && CollectionUtil.isEmpty(teamDoctorIdList)) {
            if (teamDoctorIdList == null) {
                teamDoctorIdList = new ArrayList<>();
            }
            teamDoctorIdList.add(doctorId);
        }
        return teamDoctorIdList;
    }

    /**
     * 最新测量
     */
    @ApiOperation(value = "最新测量", response = PatientShortInfo.class)
    @PostMapping("/patient/latest")
    @AutoLog(value = "最新测量", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getLatestRecord(@RequestBody @Validated LatestRecordRequest request) {
        List<Integer> teamDoctorIdList = getTeamDoctorIdList(request.getDoctorId());
        IPage<PatientShortInfo> data = patientSugarValueService.getMeasurePatientListV3(teamDoctorIdList, null, null, request.getPageNum(), request.getPageSize());
        return Result.OK(data);
    }

}
